import { useState, useEffect } from 'react'
import PageHeader from '../components/PageHeader'
import styles from '../css/Issue.module.css'
import { getIssueByPage } from '../api/issue.js'
import IssueItem from '../components/IssueItem.jsx'
import { Pagination } from 'antd'
import AddIssueBtn from '../components/AddIssueBtn.jsx'
import Recommend from '../components/Recommend.jsx'
import ScoreRank from '../components/ScoreRank.jsx'
import { useSelector } from 'react-redux'
import TypeSelect from '../components/TypeSelect'

export default function Issues() {
  const { issueTypeId } = useSelector((state) => state.type)
  // 用于存储获取到的状态列表
  const [issueInfo, setIssueInfo] = useState([])
  // 分页信息
  const [pageInfo, setPageInfo] = useState({
    current: 1, // 当前是第一页
    pageSize: 15, // 每一页显示 15 条数据
    total: 0, // 数据的总条数
  })
  // 获取数据
  useEffect(() => {
    async function fetchData() {
      const searchParams = {
        current: pageInfo.current,
        pageSize: pageInfo.pageSize,
        issueStatus: true,
      }
      if (issueTypeId !== 'all') {
        // 用户点击了分类的，那么就需要根据分类来渲染
        searchParams.typeId = issueTypeId
        // 如果按照分类来进行查询，需要重新将当前页设置为第一页
        searchParams.current = 1
      }
      const { data } = await getIssueByPage(searchParams)
      setIssueInfo(data.data)
      setPageInfo({
        current: data.currentPage,
        pageSize: data.eachPage,
        total: data.count,
      })
    }
    fetchData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pageInfo.current, pageInfo.pageSize, issueTypeId])

  let issueList = []
  for (let i = 0; i < issueInfo.length; i++) {
    issueList.push(<IssueItem key={i} issueInfo={issueInfo[i]} />)
  }
  // 分页
  const onShowSizeChange = (current, pageSize) => {
    setPageInfo({
      current,
      pageSize,
    })
    console.log(current, pageSize)
  }
  return (
    <div className={styles.container}>
      {/* 上面的头部 */}
      <PageHeader title="问答列表">
        <TypeSelect />
      </PageHeader>
      {/* 下面的列表内容区域 */}
      <div className={styles.issueContainer}>
        {/* 左边区域 */}
        <div className={styles.leftSide}>
          {issueList}
          {issueInfo.length > 0 ? (
            <div className="paginationContainer">
              <Pagination showSizeChanger onChange={onShowSizeChange} defaultCurrent={1} total={pageInfo.total} />
            </div>
          ) : (
            <div className={styles.noIssue}>有问题，就来 coder station！</div>
          )}
        </div>
        {/* 右边区域 */}
        <div className={styles.rightSide}>
          <AddIssueBtn />
          <div
            style={{
              marginBottom: '30px',
            }}
          >
            <Recommend />
          </div>
          <ScoreRank />
        </div>
      </div>
    </div>
  )
}
